interface DataType {
  key: string
  id: number
  title: string
  content: string
  createdAt: string
  tags: Array<{ name: string }>
}
type FieldType = {
  title?: string
  content?: string
  tags: Array<{ name: string }>
}
import { useEffect, useState } from "react"
import {
  Button,
  message,
  Space,
  Table,
  Modal,
  Form,
  Input,
  Tag,
  Select,
} from "antd"
import type { TableProps } from "antd"
import http from "./utils/http"
import "./App.css"
const { Search } = Input
const App = () => {
  const [tableData, setTableData] = useState()
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  // 编辑数据的Id
  const [editId, setEditId] = useState<number>()
  // 判断新增还是编辑
  const [flag, setFlag] = useState<boolean>(false)
  const [form] = Form.useForm()
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "First Name",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "Last Name",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "Username",
      dataIndex: "tags",
      key: "tags",
      render: text =>
        text.map((item: { name: string }, ind: number) => (
          <Tag key={ind}>{item.name}</Tag>
        )),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => handelEdit(record)}>编辑</Button>
          <Button type="primary" danger>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  useEffect(() => {
    getTable()
  }, [])
  // 请求表格数据
  async function getTable(title?: string) {
    try {
      const res = await http.get("/article/list", {
        params: {
          page: 1,
          pageSize: 8,
          keyword: title,
        },
      })
      if (res.status === 200) {
        setTableData(res.data.rows)
      }
    } catch (error) {}
  }

  const handleOk = () => {
    setIsModalOpen(false)
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }
  // 编辑按钮
  const handelEdit = (record: DataType) => {
    setEditId(record.id)
    setIsModalOpen(true)
    setFlag(true)
    // 数据的回显
    form.setFieldsValue({
      title: record.title,
      content: record.content,
      tags: record.tags.map(item => item.name) || [],
    })
  }
  // 新增按钮
  const handelAdd = () => {
    setIsModalOpen(true)
    setFlag(false)
    form.resetFields()
  }
  // 提交按钮
  const handelSubmit = async () => {
    try {
      // 先获取表单的数据
      const values = await form.getFieldsValue()
      // 如果为真
      if (flag) {
        // 执行编辑逻辑
        // 编辑请求的参数
        const editParmas = {
          title: values.title,
          content: values.content,
          // tagList: values.tags || [],
        }
        const res = await http.put(`/article/${editId}`, editParmas)
        console.log(res)
        if (res.status === 200 || res.status === 204) {
          message.success("编辑成功")
          getTable()
        } else {
          message.error("编辑失败")
        }
      } else {
        // 否则执行新增逻辑
        // 新增请求的参数
        const addParmas = {
          title: values.title,
          content: values.content,
          tagList: values.tags || [],
          authorId: 47529555,
        }
        const res = await http.post("/article", addParmas)
        console.log(res)
        if (res.status === 200) {
          message.success("新增成功")
          getTable()
        }
      }
    } catch (error) {}
    setIsModalOpen(false)
  }
  // 搜索
  const handelSeacrh = (e: any) => {
    const searchParmas = e.target.value
    console.log(searchParmas)
    getTable(searchParmas)
  }
  return (
    <div>
      <div className="table-search">
        <div>
          <Button type="primary" onClick={handelAdd}>
            新增
          </Button>
        </div>
        <div className="search">
          <span>搜索</span>
          <Input
            style={{ width: 200 }}
            onPressEnter={handelSeacrh}
            allowClear></Input>
        </div>
      </div>
      <Table<DataType> columns={columns} dataSource={tableData} rowKey="id" />
      <Modal
        title="信息"
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={
          <div>
            <Button onClick={handleOk}>取消</Button>,
            <Button type="primary" onClick={handelSubmit}>
              提交
            </Button>
          </div>
        }>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ minWidth: 700 }}
          autoComplete="off">
          <Form.Item<FieldType>
            label="First Name"
            name="title"
            layout="vertical">
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            label="Last Name"
            name="content"
            layout="vertical">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="Username" name="tags" layout="vertical">
            <Select mode="tags" style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default App
